import { CreditCard, Download, AlertCircle, X, CheckCircle, ChevronLeft, ChevronRight, User, Mail, MapPin, Globe, ChevronDown } from 'lucide-react';
import { useLanguage } from '@kernelproxy/i18n';
import { useState } from 'react';
import { StripePaymentModal } from '../../components/StripePaymentModal';
import { AddStripePaymentMethodModal } from '../../components/AddStripePaymentMethodModal';
import { useToast } from '../../contexts/ToastContext';

interface BillingDetails {
  fullName: string;
  email: string;
  address: string;
  country: string;
  postalCode: string;
}

type PaymentType = 'credit-card' | 'paypal' | 'usdt';

const Billing = () => {
  const { language } = useLanguage();
  const toast = useToast();
  const [showAddFundsModal, setShowAddFundsModal] = useState(false);
  const [showAddPaymentModal, setShowAddPaymentModal] = useState(false);
  const [showStripePaymentModal, setShowStripePaymentModal] = useState(false);
  const [showStripeAddPaymentModal, setShowStripeAddPaymentModal] = useState(false);
  const [selectedAmount, setSelectedAmount] = useState<number | null>(null);
  const [customAmount, setCustomAmount] = useState('');
  
  // Payment method form state
  const [paymentType, setPaymentType] = useState<PaymentType>('credit-card');
  const [paymentForm, setPaymentForm] = useState({
    // Credit Card
    cardNumber: '',
    cardholderName: '',
    expiryDate: '',
    cvv: '',
    // PayPal
    paypalEmail: '',
    // USDT
    usdtAddress: '',
    network: 'TRC20',
    // Common
    isDefault: false
  });
  
  // Billing details state
  const [billingDetails, setBillingDetails] = useState<BillingDetails>({
    fullName: '',
    email: '',
    address: '',
    country: '',
    postalCode: ''
  });
  
  // Pagination for Current Plans
  const [currentPage, setCurrentPage] = useState(1);
  const plansPerPage = 5;

  // Predefined amounts with bonus
  const fundingOptions = [
    { amount: 100, bonus: 0, totalCredit: 100 },
    { amount: 200, bonus: 10, totalCredit: 210 },
    { amount: 500, bonus: 30, totalCredit: 530 },
    { amount: 1000, bonus: 100, totalCredit: 1100 },
    { amount: 2000, bonus: 250, totalCredit: 2250 },
    { amount: 5000, bonus: 750, totalCredit: 5750 },
  ];

  const calculateBonus = (amount: number): { bonus: number; totalCredit: number } => {
    if (amount >= 5000) {
      const bonus = Math.floor(amount * 0.15);
      return { bonus, totalCredit: amount + bonus };
    } else if (amount >= 2000) {
      const bonus = Math.floor(amount * 0.125);
      return { bonus, totalCredit: amount + bonus };
    } else if (amount >= 1000) {
      const bonus = Math.floor(amount * 0.10);
      return { bonus, totalCredit: amount + bonus };
    } else if (amount >= 500) {
      const bonus = Math.floor(amount * 0.06);
      return { bonus, totalCredit: amount + bonus };
    } else if (amount >= 200) {
      const bonus = Math.floor(amount * 0.05);
      return { bonus, totalCredit: amount + bonus };
    }
    return { bonus: 0, totalCredit: amount };
  };

  const handleCustomAmountChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setCustomAmount(value);
    setSelectedAmount(null);
  };

  const handleAddFunds = () => {
    const amount = selectedAmount || parseFloat(customAmount);
    if (amount && amount >= 0.50) {
      const { bonus, totalCredit } = calculateBonus(amount);
      console.log('Adding funds:', { amount, bonus, totalCredit });
      // Open Stripe payment modal
      setShowStripePaymentModal(true);
    }
  };

  const getDisplayedBonus = () => {
    const amount = selectedAmount || parseFloat(customAmount) || 0;
    return calculateBonus(amount);
  };

  const plans = [
    {
      type: 'dynamic',
      name: language === 'zh-CN' ? '动态住宅代理' : 'Dynamic Residential',
      pricing: language === 'zh-CN' ? '按流量计费' : 'Pay-per-GB',
      usage: '420 GB',
      cost: '$210.00',
      rate: '$0.50/GB',
    },
    {
      type: 'static',
      name: language === 'zh-CN' ? '静态住宅代理' : 'Static Residential',
      pricing: language === 'zh-CN' ? '按月计费' : 'Monthly',
      usage: '45 IPs',
      cost: '$450.00',
      rate: '$10/IP/month',
    },
    {
      type: 'ipv6',
      name: language === 'zh-CN' ? 'IPv6代理' : 'IPv6 Proxy',
      pricing: language === 'zh-CN' ? '按周计费' : 'Weekly',
      usage: '150 GB',
      cost: '$75.00',
      rate: '$0.50/GB/week',
    },
    {
      type: 'dynamic',
      name: language === 'zh-CN' ? '动态数据中心代理' : 'Dynamic Datacenter',
      pricing: language === 'zh-CN' ? '按流量计费' : 'Pay-per-GB',
      usage: '280 GB',
      cost: '$84.00',
      rate: '$0.30/GB',
    },
    {
      type: 'static',
      name: language === 'zh-CN' ? '静态数据中心代理' : 'Static Datacenter',
      pricing: language === 'zh-CN' ? '按月计费' : 'Monthly',
      usage: '20 IPs',
      cost: '$100.00',
      rate: '$5/IP/month',
    },
    {
      type: 'mobile',
      name: language === 'zh-CN' ? '移动代理' : 'Mobile Proxy',
      pricing: language === 'zh-CN' ? '按流量计费' : 'Pay-per-GB',
      usage: '50 GB',
      cost: '$75.00',
      rate: '$1.50/GB',
    },
  ];

  // Pagination calculations for plans
  const totalPlanPages = Math.ceil(plans.length / plansPerPage);
  const startPlanIndex = (currentPage - 1) * plansPerPage;
  const endPlanIndex = startPlanIndex + plansPerPage;
  const currentPlans = plans.slice(startPlanIndex, endPlanIndex);

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const invoices = [
    { id: 'INV-2025-001', date: '2025-10-01', amount: '$735.00', status: 'paid' },
    { id: 'INV-2025-002', date: '2025-09-01', amount: '$680.00', status: 'paid' },
    { id: 'INV-2025-003', date: '2025-08-01', amount: '$590.00', status: 'paid' },
  ];

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
          {language === 'zh-CN' ? '计费与套餐' : 'Billing & Plans'}
        </h1>
        <p className="text-gray-600 dark:text-gray-400 mt-2">
          {language === 'zh-CN' ? '管理您的套餐和账单' : 'Manage your plans and billing'}
        </p>
      </div>

      {/* Account Balance */}
      <div className="bg-gradient-to-br from-blue-600 to-purple-600 rounded-lg shadow-lg p-8 text-white">
        <div className="flex items-center justify-between">
          <div>
            <p className="text-blue-100 mb-2">{language === 'zh-CN' ? '账户余额' : 'Account Balance'}</p>
            <p className="text-4xl font-bold">$1,250.00</p>
            <p className="text-blue-100 mt-2">
              {language === 'zh-CN' ? '本月消费: ' : 'This month: '}$735.00
            </p>
          </div>
          <button 
            onClick={() => setShowAddFundsModal(true)}
            className="px-6 py-3 bg-white text-blue-600 font-medium rounded-lg hover:bg-blue-50 transition-colors"
          >
            {language === 'zh-CN' ? '充值' : 'Add Funds'}
          </button>
        </div>
      </div>

      {/* Low Balance Warning */}
      <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
        <div className="flex items-start space-x-3">
          <AlertCircle className="w-5 h-5 text-yellow-600 dark:text-yellow-400 mt-0.5" />
          <div>
            <h3 className="font-medium text-yellow-900 dark:text-yellow-200">
              {language === 'zh-CN' ? '余额预警' : 'Low Balance Alert'}
            </h3>
            <p className="text-sm text-yellow-700 dark:text-yellow-300 mt-1">
              {language === 'zh-CN' 
                ? '您的账户余额低于预警阈值，请及时充值以避免服务中断。' 
                : 'Your account balance is below the warning threshold. Please add funds to avoid service interruption.'}
            </p>
          </div>
        </div>
      </div>

      {/* Current Plans */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6">
        <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-4">
          {language === 'zh-CN' ? '当前套餐' : 'Current Plans'}
        </h2>
        <div className="space-y-4">
          {currentPlans.map((plan, index) => (
            <div key={index} className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg">
              <div className="flex items-center justify-between mb-3">
                <div>
                  <h3 className="font-medium text-gray-900 dark:text-white text-lg">{plan.name}</h3>
                  <p className="text-sm text-gray-600 dark:text-gray-400">{plan.pricing}</p>
                </div>
                <div className="text-right">
                  <p className="text-2xl font-bold text-gray-900 dark:text-white">{plan.cost}</p>
                  <p className="text-sm text-gray-500 dark:text-gray-400">{plan.rate}</p>
                </div>
              </div>
              <div className="flex items-center justify-between text-sm">
                <span className="text-gray-600 dark:text-gray-400">
                  {language === 'zh-CN' ? '本月使用量' : 'This month usage'}
                </span>
                <span className="font-medium text-gray-900 dark:text-white">{plan.usage}</span>
              </div>
            </div>
          ))}
        </div>

        {/* Pagination */}
        {totalPlanPages > 1 && (
          <div className="flex items-center justify-between mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
            <div className="text-sm text-gray-600 dark:text-gray-400">
              {language === 'zh-CN' 
                ? `显示 ${startPlanIndex + 1}-${Math.min(endPlanIndex, plans.length)} / 共 ${plans.length} 个套餐`
                : `Showing ${startPlanIndex + 1}-${Math.min(endPlanIndex, plans.length)} of ${plans.length} plans`}
            </div>
            <div className="flex items-center space-x-2">
              <button
                onClick={() => handlePageChange(currentPage - 1)}
                disabled={currentPage === 1}
                className="px-3 py-1.5 rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <ChevronLeft className="w-4 h-4" />
              </button>
              
              {Array.from({ length: totalPlanPages }, (_, i) => i + 1).map((page) => (
                <button
                  key={page}
                  onClick={() => handlePageChange(page)}
                  className={`px-3 py-1.5 rounded-lg transition-colors ${
                    currentPage === page
                      ? 'bg-blue-600 text-white'
                      : 'border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
                  }`}
                >
                  {page}
                </button>
              ))}

              <button
                onClick={() => handlePageChange(currentPage + 1)}
                disabled={currentPage === totalPlanPages}
                className="px-3 py-1.5 rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <ChevronRight className="w-4 h-4" />
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Invoices */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-xl font-bold text-gray-900 dark:text-white">
            {language === 'zh-CN' ? '账单历史' : 'Invoice History'}
          </h2>
          <button className="text-blue-600 dark:text-blue-400 hover:underline text-sm">
            {language === 'zh-CN' ? '查看全部' : 'View All'}
          </button>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-gray-200 dark:border-gray-700">
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-600 dark:text-gray-400">
                  {language === 'zh-CN' ? '账单号' : 'Invoice ID'}
                </th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-600 dark:text-gray-400">
                  {language === 'zh-CN' ? '日期' : 'Date'}
                </th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-600 dark:text-gray-400">
                  {language === 'zh-CN' ? '金额' : 'Amount'}
                </th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-600 dark:text-gray-400">
                  {language === 'zh-CN' ? '状态' : 'Status'}
                </th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-600 dark:text-gray-400">
                  {language === 'zh-CN' ? '操作' : 'Action'}
                </th>
              </tr>
            </thead>
            <tbody>
              {invoices.map((invoice) => (
                <tr key={invoice.id} className="border-b border-gray-100 dark:border-gray-700/50 hover:bg-gray-50 dark:hover:bg-gray-700/30">
                  <td className="py-3 px-4 text-sm font-mono text-gray-900 dark:text-white">
                    {invoice.id}
                  </td>
                  <td className="py-3 px-4 text-sm text-gray-600 dark:text-gray-400">
                    {invoice.date}
                  </td>
                  <td className="py-3 px-4 text-sm font-medium text-gray-900 dark:text-white">
                    {invoice.amount}
                  </td>
                  <td className="py-3 px-4">
                    <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-400">
                      {language === 'zh-CN' ? '已支付' : 'Paid'}
                    </span>
                  </td>
                  <td className="py-3 px-4">
                    <button className="text-blue-600 dark:text-blue-400 hover:underline text-sm flex items-center space-x-1">
                      <Download className="w-4 h-4" />
                      <span>{language === 'zh-CN' ? '下载' : 'Download'}</span>
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Billing Details */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6">
        <div className="flex items-center space-x-2 mb-6">
          <User className="w-5 h-5 text-blue-600 dark:text-blue-400" />
          <h2 className="text-xl font-bold text-gray-900 dark:text-white">
            {language === 'zh-CN' ? '账单信息' : 'Billing Details'}
          </h2>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              {language === 'zh-CN' ? '姓名' : 'Full Name'} *
            </label>
            <div className="relative">
              <User className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
              <input
                type="text"
                value={billingDetails.fullName}
                onChange={(e) => setBillingDetails({ ...billingDetails, fullName: e.target.value })}
                placeholder={language === 'zh-CN' ? '请输入您的姓名' : 'Enter your full name'}
                className="w-full pl-10 pr-4 py-3 bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 focus:border-transparent text-gray-900 dark:text-white transition-all"
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              {language === 'zh-CN' ? '邮箱' : 'Email'} *
            </label>
            <div className="relative">
              <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
              <input
                type="email"
                value={billingDetails.email}
                onChange={(e) => setBillingDetails({ ...billingDetails, email: e.target.value })}
                placeholder={language === 'zh-CN' ? '请输入您的邮箱' : 'Enter your email'}
                className="w-full pl-10 pr-4 py-3 bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 focus:border-transparent text-gray-900 dark:text-white transition-all"
              />
            </div>
          </div>

          <div className="md:col-span-2">
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              {language === 'zh-CN' ? '地址' : 'Address'} *
            </label>
            <div className="relative">
              <MapPin className="absolute left-3 top-3 text-gray-400" size={18} />
              <input
                type="text"
                value={billingDetails.address}
                onChange={(e) => setBillingDetails({ ...billingDetails, address: e.target.value })}
                placeholder={language === 'zh-CN' ? '请输入您的地址' : 'Enter your address'}
                className="w-full pl-10 pr-4 py-3 bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 focus:border-transparent text-gray-900 dark:text-white transition-all"
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              {language === 'zh-CN' ? '国家' : 'Country'} *
            </label>
            <div className="relative">
              <Globe className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
              <input
                type="text"
                value={billingDetails.country}
                onChange={(e) => setBillingDetails({ ...billingDetails, country: e.target.value })}
                placeholder={language === 'zh-CN' ? '请输入国家' : 'Enter country'}
                className="w-full pl-10 pr-4 py-3 bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 focus:border-transparent text-gray-900 dark:text-white transition-all"
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              {language === 'zh-CN' ? '邮编' : 'Postal Code'} *
            </label>
            <input
              type="text"
              value={billingDetails.postalCode}
              onChange={(e) => setBillingDetails({ ...billingDetails, postalCode: e.target.value })}
              placeholder={language === 'zh-CN' ? '请输入邮编' : 'Enter postal code'}
              className="w-full px-4 py-3 bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 focus:border-transparent text-gray-900 dark:text-white transition-all"
            />
          </div>
        </div>

        <div className="mt-6 flex justify-end">
          <button className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
            {language === 'zh-CN' ? '保存账单信息' : 'Save Billing Details'}
          </button>
        </div>

        {/* Note */}
        <div className="mt-4 p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
          <p className="text-sm text-blue-700 dark:text-blue-300">
            {language === 'zh-CN' 
              ? '请确保填写正确的账单信息，这些信息将用于支付和开具发票。'
              : 'Please ensure your billing information is correct. This will be used for payments and invoicing.'}
          </p>
        </div>
      </div>

      {/* Add Funds Modal */}
      {showAddFundsModal && (
        <div 
          className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 transition-opacity duration-300"
          onClick={() => setShowAddFundsModal(false)}
        >
          <div 
            className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-2xl w-full mx-4 transform transition-all duration-300"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Modal Header */}
            <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
              <h3 className="text-xl font-bold text-gray-900 dark:text-white">
                {language === 'zh-CN' ? '充值账户' : 'Add Funds to Account'}
              </h3>
              <button
                onClick={() => setShowAddFundsModal(false)}
                className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
              >
                <X className="w-6 h-6" />
              </button>
            </div>

            {/* Modal Body */}
            <div className="p-6 space-y-6">
              {/* Bonus Info Banner */}
              <div className="bg-gradient-to-r from-blue-50 to-purple-50 dark:from-blue-900/20 dark:to-purple-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
                <div className="flex items-start">
                  <CheckCircle className="w-5 h-5 text-blue-600 dark:text-blue-400 mt-0.5 mr-3 flex-shrink-0" />
                  <div>
                    <h4 className="font-semibold text-blue-900 dark:text-blue-200 mb-1">
                      {language === 'zh-CN' ? '充值奖励政策' : 'Bonus Credit Policy'}
                    </h4>
                    <ul className="text-sm text-blue-800 dark:text-blue-300 space-y-1">
                      <li>• {language === 'zh-CN' ? '充值 $200+ 额外获得 5% Credit' : 'Recharge $200+: Extra 5% Credit'}</li>
                      <li>• {language === 'zh-CN' ? '充值 $500+ 额外获得 6% Credit' : 'Recharge $500+: Extra 6% Credit'}</li>
                      <li>• {language === 'zh-CN' ? '充值 $1000+ 额外获得 10% Credit' : 'Recharge $1000+: Extra 10% Credit'}</li>
                      <li>• {language === 'zh-CN' ? '充值 $2000+ 额外获得 12.5% Credit' : 'Recharge $2000+: Extra 12.5% Credit'}</li>
                      <li>• {language === 'zh-CN' ? '充值 $5000+ 额外获得 15% Credit' : 'Recharge $5000+: Extra 15% Credit'}</li>
                    </ul>
                  </div>
                </div>
              </div>

              {/* Predefined Amounts */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                  {language === 'zh-CN' ? '选择充值金额' : 'Select Amount'}
                </label>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                  {fundingOptions.map((option) => (
                    <button
                      key={option.amount}
                      onClick={() => {
                        setSelectedAmount(option.amount);
                        setCustomAmount('');
                      }}
                      className={`p-4 rounded-lg border-2 transition-all ${
                        selectedAmount === option.amount
                          ? 'border-blue-600 bg-blue-50 dark:bg-blue-900/20'
                          : 'border-gray-200 dark:border-gray-600 hover:border-blue-400'
                      }`}
                    >
                      <div className="text-center">
                        <p className="text-2xl font-bold text-gray-900 dark:text-white">
                          ${option.amount}
                        </p>
                        {option.bonus > 0 && (
                          <p className="text-xs text-green-600 dark:text-green-400 mt-1">
                            +${option.bonus} {language === 'zh-CN' ? '奖励' : 'Bonus'}
                          </p>
                        )}
                        <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                          = ${option.totalCredit}
                        </p>
                      </div>
                    </button>
                  ))}
                </div>
              </div>

              {/* Custom Amount */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  {language === 'zh-CN' ? '或输入自定义金额 (最低 $0.50)' : 'Or Enter Custom Amount (Min $0.50)'}
                </label>
                <div className="relative">
                  <span className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-500 dark:text-gray-400">$</span>
                  <input
                    type="number"
                    min="0.50"
                    step="0.01"
                    value={customAmount}
                    onChange={handleCustomAmountChange}
                    placeholder="0.00"
                    className="w-full pl-8 pr-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500"
                  />
                </div>
              </div>

              {/* Summary */}
              {(selectedAmount || parseFloat(customAmount) >= 0.50) && (
                <div className="bg-gray-50 dark:bg-gray-900/50 rounded-lg p-4 space-y-2">
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-600 dark:text-gray-400">
                      {language === 'zh-CN' ? '充值金额' : 'Recharge Amount'}
                    </span>
                    <span className="font-medium text-gray-900 dark:text-white">
                      ${selectedAmount || parseFloat(customAmount).toFixed(2)}
                    </span>
                  </div>
                  {getDisplayedBonus().bonus > 0 && (
                    <div className="flex justify-between text-sm">
                      <span className="text-green-600 dark:text-green-400">
                        {language === 'zh-CN' ? '奖励 Credit' : 'Bonus Credit'}
                      </span>
                      <span className="font-medium text-green-600 dark:text-green-400">
                        +${getDisplayedBonus().bonus}
                      </span>
                    </div>
                  )}
                  <div className="flex justify-between text-base font-bold pt-2 border-t border-gray-200 dark:border-gray-700">
                    <span className="text-gray-900 dark:text-white">
                      {language === 'zh-CN' ? '总 Credit' : 'Total Credit'}
                    </span>
                    <span className="text-blue-600 dark:text-blue-400">
                      ${getDisplayedBonus().totalCredit}
                    </span>
                  </div>
                </div>
              )}
            </div>

            {/* Modal Footer */}
            <div className="flex justify-end gap-3 p-6 border-t border-gray-200 dark:border-gray-700">
              <button
                onClick={() => setShowAddFundsModal(false)}
                className="px-6 py-2 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors"
              >
                {language === 'zh-CN' ? '取消' : 'Cancel'}
              </button>
              <button
                onClick={handleAddFunds}
                disabled={!selectedAmount && (!customAmount || parseFloat(customAmount) < 0.50)}
                className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {language === 'zh-CN' ? '确认充值' : 'Confirm Recharge'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Add Payment Method Modal */}
      {showAddPaymentModal && (
        <div 
          className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 transition-opacity duration-300"
          onClick={() => setShowAddPaymentModal(false)}
        >
          <div 
            className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full mx-4 transform transition-all duration-300"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Modal Header */}
            <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
              <h3 className="text-xl font-bold text-gray-900 dark:text-white">
                {language === 'zh-CN' ? '添加支付方式' : 'Add Payment Method'}
              </h3>
              <button
                onClick={() => setShowAddPaymentModal(false)}
                className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Modal Body */}
            <div className="p-6 space-y-4">
              {/* Payment Type Selector */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  {language === 'zh-CN' ? '支付方式类型' : 'Payment Type'}
                </label>
                <div className="grid grid-cols-3 gap-2">
                  <button
                    onClick={() => setPaymentType('credit-card')}
                    className={`px-4 py-3 rounded-lg border-2 transition-all ${
                      paymentType === 'credit-card'
                        ? 'border-blue-600 bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400'
                        : 'border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:border-gray-400'
                    }`}
                  >
                    <CreditCard className="w-5 h-5 mx-auto mb-1" />
                    <span className="text-xs font-medium">
                      {language === 'zh-CN' ? '信用卡' : 'Card'}
                    </span>
                  </button>
                  <button
                    onClick={() => setPaymentType('paypal')}
                    className={`px-4 py-3 rounded-lg border-2 transition-all ${
                      paymentType === 'paypal'
                        ? 'border-blue-600 bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400'
                        : 'border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:border-gray-400'
                    }`}
                  >
                    <div className="text-xs font-bold mx-auto mb-1">PayPal</div>
                    <span className="text-xs font-medium">PayPal</span>
                  </button>
                  <button
                    onClick={() => setPaymentType('usdt')}
                    className={`px-4 py-3 rounded-lg border-2 transition-all ${
                      paymentType === 'usdt'
                        ? 'border-blue-600 bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400'
                        : 'border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:border-gray-400'
                    }`}
                  >
                    <div className="text-xs font-bold mx-auto mb-1">USDT</div>
                    <span className="text-xs font-medium">USDT</span>
                  </button>
                </div>
              </div>

              {/* Credit Card Fields */}
              {paymentType === 'credit-card' && (
                <>
                  {/* Card Number */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      {language === 'zh-CN' ? '卡号' : 'Card Number'}
                    </label>
                    <input
                      type="text"
                      placeholder="1234 5678 9012 3456"
                      value={paymentForm.cardNumber}
                      onChange={(e) => setPaymentForm({ ...paymentForm, cardNumber: e.target.value })}
                      className="w-full px-4 py-2 bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      maxLength={19}
                    />
                  </div>

                  {/* Cardholder Name */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      {language === 'zh-CN' ? '持卡人姓名' : 'Cardholder Name'}
                    </label>
                    <input
                      type="text"
                      placeholder="John Doe"
                      value={paymentForm.cardholderName}
                      onChange={(e) => setPaymentForm({ ...paymentForm, cardholderName: e.target.value })}
                      className="w-full px-4 py-2 bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    />
                  </div>

                  {/* Expiry Date and CVV */}
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        {language === 'zh-CN' ? '到期日期' : 'Expiry Date'}
                      </label>
                      <input
                        type="text"
                        placeholder="MM/YY"
                        value={paymentForm.expiryDate}
                        onChange={(e) => setPaymentForm({ ...paymentForm, expiryDate: e.target.value })}
                        className="w-full px-4 py-2 bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        maxLength={5}
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        CVV
                      </label>
                      <input
                        type="text"
                        placeholder="123"
                        value={paymentForm.cvv}
                        onChange={(e) => setPaymentForm({ ...paymentForm, cvv: e.target.value })}
                        className="w-full px-4 py-2 bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        maxLength={4}
                      />
                    </div>
                  </div>
                </>
              )}

              {/* PayPal Fields */}
              {paymentType === 'paypal' && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    {language === 'zh-CN' ? 'PayPal邮箱' : 'PayPal Email'}
                  </label>
                  <input
                    type="email"
                    placeholder="user@example.com"
                    value={paymentForm.paypalEmail}
                    onChange={(e) => setPaymentForm({ ...paymentForm, paypalEmail: e.target.value })}
                    className="w-full px-4 py-2 bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>
              )}

              {/* USDT Fields */}
              {paymentType === 'usdt' && (
                <>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      {language === 'zh-CN' ? 'USDT钱包地址' : 'USDT Wallet Address'}
                    </label>
                    <input
                      type="text"
                      placeholder="T9yD...xK7p"
                      value={paymentForm.usdtAddress}
                      onChange={(e) => setPaymentForm({ ...paymentForm, usdtAddress: e.target.value })}
                      className="w-full px-4 py-2 bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      {language === 'zh-CN' ? '网络' : 'Network'}
                    </label>
                    <div className="relative">
                      <select
                        value={paymentForm.network}
                        onChange={(e) => setPaymentForm({ ...paymentForm, network: e.target.value })}
                        className="w-full pl-4 pr-10 py-2 bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent appearance-none cursor-pointer"
                      >
                        <option value="TRC20">TRC20</option>
                        <option value="ERC20">ERC20</option>
                        <option value="BEP20">BEP20</option>
                      </select>
                      <ChevronDown className="absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
                    </div>
                  </div>
                </>
              )}

              {/* Set as Default */}
              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="setAsDefault"
                  checked={paymentForm.isDefault}
                  onChange={(e) => setPaymentForm({ ...paymentForm, isDefault: e.target.checked })}
                  className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
                />
                <label htmlFor="setAsDefault" className="ml-2 text-sm text-gray-700 dark:text-gray-300">
                  {language === 'zh-CN' ? '设为默认支付方式' : 'Set as default payment method'}
                </label>
              </div>
            </div>

            {/* Modal Footer */}
            <div className="flex justify-end gap-3 p-6 border-t border-gray-200 dark:border-gray-700">
              <button
                onClick={() => setShowAddPaymentModal(false)}
                className="px-6 py-2 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors"
              >
                {language === 'zh-CN' ? '取消' : 'Cancel'}
              </button>
              <button
                onClick={() => {
                  // TODO: Implement payment method save logic
                  setShowAddPaymentModal(false);
                  setPaymentType('credit-card');
                  setPaymentForm({
                    cardNumber: '',
                    cardholderName: '',
                    expiryDate: '',
                    cvv: '',
                    paypalEmail: '',
                    usdtAddress: '',
                    network: 'TRC20',
                    isDefault: false
                  });
                }}
                className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
              >
                {language === 'zh-CN' ? '添加' : 'Add'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Stripe Payment Modal for Adding Funds */}
      <StripePaymentModal
        isOpen={showStripePaymentModal}
        amount={selectedAmount || parseFloat(customAmount) || 0}
        onSuccess={() => {
          setShowStripePaymentModal(false);
          setShowAddFundsModal(false);
          setSelectedAmount(null);
          setCustomAmount('');
          toast.success(language === 'zh-CN' ? '充值成功！' : 'Funds added successfully!');
        }}
        onClose={() => setShowStripePaymentModal(false)}
      />

      {/* Stripe Add Payment Method Modal */}
      <AddStripePaymentMethodModal
        isOpen={showStripeAddPaymentModal}
        onSuccess={(paymentMethodId) => {
          setShowStripeAddPaymentModal(false);
          console.log('Payment method added:', paymentMethodId);
          // TODO: Save payment method to your backend
        }}
        onClose={() => setShowStripeAddPaymentModal(false)}
      />
    </div>
  );
};

export default Billing;
